<template>
  <div v-loading.fullscreen.lock="fullscreenLoading" class="newsadd" :style="{minHeight:screenHeight}">
    <div class="namediv nameinput1">
      {{dialogform.aname}}
    </div>
    <div class="content" v-for="item,index in dialogform.content" :key="index">
      <div v-if="item.type == 'text'">
        <el-popover
          v-if="item.sign"
          placement="right"
          width="80"
          trigger="hover">
          <el-button 
              type="primary" 
              style="margin-bottom:5px;" 
              @click="item.sign = false" >
              修改
          </el-button>
          <el-button 
              type="danger" 
              @click="clear(index)" >
              删除
          </el-button>
          <div  slot="reference" class="contentText">
            &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;{{item.content}}
          </div>
        </el-popover>
        <div class="addtext" v-else>
          <textarea placeholder="请输入新闻内容" class="addinput" v-model="item.content" type="text"></textarea>
          <div class="addtextbutton">
            <el-button size="mini" @click="item.sign = true">完成</el-button>
          </div>
        </div>
      </div>
       <el-popover
        v-else
				placement="right"
				width="100"
				trigger="hover">
        <el-button 
            type="primary" 
            style="margin-bottom:5px;" 
            @click="$refs.editimgfile.click();imgIndex = index;" >
            修改
        </el-button>
        <el-button 
            type="danger" 
            @click="clear(index)" >
            删除
        </el-button>
        <div slot="reference" class="imgdiv">
          <div class="contentImg">
            <el-image
              style="width:650px;height:350px;"
              :src="item.content"
              :fit="'cover'">
              <div slot="error" class="image-slot">
                <i class="el-icon-picture-outline"></i>
              </div>
            </el-image>
          </div>
        </div>
      </el-popover>
    </div>
    <div class="addtext" v-show="showtext">
      <textarea placeholder="请输入新闻内容" class="addinput" v-model="contentText" type="text"></textarea>
      <div class="addtextbutton">
        <el-button size="mini" @click="addtext">完成</el-button>
      </div>
    </div>
    <input type="file" ref="editimgfile" v-show="false"  @change="editimgfile()"/>
    <input type="file" ref="imgfile" v-show="false"  @change="addimg()"/>
    <input type="file" ref="imgback" v-show="false"  @change="addimgimgback()"/>
    <!-- 创建新闻弹窗 -->
    <div v-loading="fullscreenLoading" class="dialog" v-if="dialogFormVisible">
      <div class="dialog-content">
        <div class="diglog-name">创建新闻</div>
        <el-form ref="formregister" :model="dialogform" :rules="registerrules" width="500">
          <el-form-item label="新闻封面:" label-width="100px" prop="cover" class="imgform">
            <div v-if="dialogform.cover != ''">
                <el-image
                  @click="$refs.imgback.click()"
                  style="width:220px;height:100px;cursor: pointer;"
                  :src="dialogform.cover"
                  :fit="'fit'">
                </el-image>
            </div>
            <div v-else @click="$refs.imgback.click()" class="addimg">
              +
            </div>
          </el-form-item>
          <el-form-item label="新闻类型:" prop="atype" label-width="100px">
            <el-select v-model="dialogform.atype" placeholder="请选择">
              <el-option
                v-for="item in newTypeoptions"
                :key="item.value"
                :label="item.label"
                :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="新闻名称:" prop="aname" label-width="100px">
            <el-input v-model="dialogform.aname" placeholder="请输入新闻名称" ></el-input>
          </el-form-item>
          <el-form-item label="作者名称:" prop="author" label-width="100px">
            <el-input v-model="dialogform.author" placeholder="请输入作者名称" ></el-input>
          </el-form-item>
          <el-form-item label="新闻简介:" prop="ainformation" label-width="100px">
            <el-input 
            :show-word-limit="true"
            maxlength="80"
            style="min-height: 0;"
            placeholder="请输入新闻简介"
            class="addinput"
            v-model="dialogform.ainformation" 
            type="textarea"></el-input>
          </el-form-item>
        </el-form>
        <div class="dialog-footer">
          <!-- <el-button @click="dialogNo">取 消</el-button> -->
          <el-button type="primary" @click="dialogYes">确 定</el-button>
        </div>
      </div>
    </div>
    <div class="addbutton">
      <el-popover
        v-model="popover"
        placement="top-start"
        trigger="hover">
        <div>
          <el-button
            type="warning"
            style="margin-right:5px;"
            @click="popover = false;showtext = true" >
            添加文字
          </el-button>
          <el-tooltip
            class="item"
            style="margin-right:5px;" 
            effect="dark" 
            content="请添加图片，大小不超过4MB！" 
            placement="top-start">
            <el-button 
              type="primary"
              @click="$refs.imgfile.click();popover = false;" >
              添加图片
            </el-button>
          </el-tooltip>
          <el-button 
            type="danger" 
            style="margin-right:5px;" 
            @click="dialogFormVisible = true;popover = false;" >
            编辑详情
          </el-button>
          <el-button 
            type="success" 
            @click="dialogVisible = true;popover = false;">
            保存新闻
          </el-button>
        </div>
        <el-button slot="reference" type="primary" icon="el-icon-edit" circle></el-button>
      </el-popover>
      <el-dialog
        title="提示"
        :modal="false"
        :visible.sync="dialogVisible"
        width="300px">
        <span>请您确认保存编辑?</span>
        <span slot="footer" class="dialog-footer">
          <el-button @click="dialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="confirm">确 定</el-button>
        </span>
      </el-dialog>
    </div>
  </div>
</template>
<script>
import * as imageConversion from 'image-conversion'//压缩图片引入
export default {
  data(){
    return{
      editid:'',
      fullscreenLoading:false,
      dialogVisible:false,
      popover:false,
      dialogFormVisible:false,
      gourl:'',
      screenHeight:'',
      imgIndex:-1,
      contentText:'',
      showtext:false,
      dialogform:{
        _id:'',
        ainformation:'',//新闻简介
        aname:'',//新闻名称
        cover:'',//封面
        atype:'',//类型
        author:'',//作者
        pubilshDate:'',//发布时间
        afabu:false,//是否发布
        aredu:0,//热度
        fanwen:0,//访问量
        content:[]
      },
      registerrules:{
          author: [
              {required: true,message: '请输入作者名称', trigger: 'blur' }
          ],
          atype: [
              {required: true,message: '请选择新闻类型', trigger: 'change' },
          ],
          aname: [
            { required: true, message: '请输入新闻名称', trigger: 'blur' },
            { min: 4, max: 30, message: '名称长度为4-30个字符', trigger: 'blur' }
          ],
          cover: [
            {required: true, message: '请添加新闻封面', trigger: 'change' }
          ],
          ainformation:[
            { required: true, message: '请输入新闻简介', trigger: 'blur' },
            { min: 20, max: 80, message: '新闻简介控制在20-80字以内', trigger: 'blur' }
          ],
      },
      newTypeoptions:[
        {
          value:'军事',
          lable:'军事'
        },
        {
          value:'娱乐',
          lable:'娱乐'
        },
        {
          value:'生活',
          lable:'生活'
        },
        {
          value:'国际',
          lable:'国际'
        },
        {
          value:'体育',
          lable:'体育'
        },
        {
          value:'科技',
          lable:'科技'
        }
      ],
    }
  },
  watch:{
    $route(to,pre){
      this.gourl = pre.fullPath
      if(to.fullPath == "/management/newsAdd"){
        let id = sessionStorage.getItem('editID')
        if(id !== ''){
          this.editid = id
          sessionStorage.setItem('editID','')
          this.query()
        }
      }
    }
  },
  created(){
    this.dialogFormVisible = true
    this.screenHeight = (window.innerHeight - 110) + 'px'
    let id = sessionStorage.getItem('editID')
    if(id !== ''){
      this.editid = id
      sessionStorage.setItem('editID','')
      this.query()
    }
  },
  methods:{
    //删除新闻
    clear(index){
      this.dialogform.content.splice(index,1)
    },
    //修改图片
    async editimgfile(){
      if(this.imgIndex == -1) return
      let files = this.$refs.editimgfile.files[0];
      let name = ['jpg','png','jpge']
      let na = files.name.split('.')
      let i = name.findIndex(item => item.toLocaleUpperCase() == na[1].toLocaleUpperCase())
      if(i == -1){
        this.$message.warning('仅支持png、jpg、jpge格式图片')
        return
      }
      if(files.size/1024/1024 > 4){
        this.$message.warning('图片最大支持4MB')
        return
      }
      let file = await this.compressImg(files)
      var reader = new FileReader();
      reader.readAsDataURL(file); //调用自带方法进行转换
      reader.onload = (e) => {
        this.dialogform.content[this.imgIndex].content = e.target.result,
        this.imgIndex = -1
      }
    },
    //添加图片
    async addimg(){
      let files = this.$refs.imgfile.files[0];
      let name = ['jpg','png','jpge']
      let na = files.name.split('.')
      let i = name.findIndex(item => item.toLocaleUpperCase() == na[1].toLocaleUpperCase())
      if(i == -1){
        this.$message.warning('仅支持png、jpg、jpge格式图片')
        return
      }
      if(files.size/1024/1024 > 4){
        this.$message.warning('图片最大支持4MB')
        return
      }
      let file = await this.compressImg(files)
      var reader = new FileReader();
      reader.readAsDataURL(file); //调用自带方法进行转换
      reader.onload = (e) => {
        let list = {
          content:e.target.result,
          type:'img',
          sign:true,
          index:this.dialogform.content.length+1
        }
      this.dialogform.content.push(list)
      }
    },
    async addimgimgback(){
      let files = this.$refs.imgback.files[0];
      let name = ['jpg','png','jpge']
      let na = files.name.split('.')
      let i = name.findIndex(item => item.toLocaleUpperCase() == na[1].toLocaleUpperCase())
      if(i == -1){
        this.$message.warning('仅支持png、jpg、jpge格式图片')
        return
      }
      if(files.size/1024/1024 > 4){
        this.$message.warning('图片最大支持4MB')
        return
      }
      let file = await this.compressImg1(files)
      var reader = new FileReader();
      reader.readAsDataURL(file); //调用自带方法进行转换
      reader.onload = (e) => {
        this.dialogform.cover = e.target.result
      }
    },
    compressImg1(file){
      return new Promise((resolve, reject) => {
          imageConversion.compressAccurately(file, 50).then(res => {
            res = new File([res], file.name, { type: res.type, lastModified: Date.now() })
            resolve(res)
          })
      })
    },
    compressImg(file){
      return new Promise((resolve, reject) => {
          imageConversion.compressAccurately(file, 100).then(res => {
            res = new File([res], file.name, { type: res.type, lastModified: Date.now() })
            resolve(res)
          })
      })
    },
    //添加文字
    addtext(){
      if(this.contentText !== ''){
      let list = {
        content:this.contentText,
        type:'text',
        sign:true,
        index:this.dialogform.content.length+1
      }
      this.dialogform.content.push(list)
      this.contentText = ''
      this.showtext = false
      }
    },
    //取消新建新闻
    dialogNo(){
      this.dialogFormVisible = false
    },
    //确认新建新闻
    dialogYes(){
      this.$refs['formregister'].validate((valid) => {
        if(valid){
          this.dialogFormVisible = false
        }
      })
    },
    //保存新闻
    confirm(){
      this.fullscreenLoading = true
      // let t = new Date()
      // let fn1 = (d) =>('0'+d).substr(-2)
      // let datatime = t.getFullYear()+'-'+ fn1(t.getMonth()+1)+'-'+ fn1(t.getDate())
      // this.dialogform.pubilshDate = datatime
      this.dialogform.aid = this.dialogform._id
      this.$http.post(this.editid == ''?'/artcate/add':'/artcate/bianji',this.dialogform).then(res => {
        this.fullscreenLoading = false
        if(res.status == 0){
          sessionStorage.setItem('editID','')
          this.dialogVisible = false
          this.editid = ''
          this.dialogform = {
            _id:'',
            aname:'',//新闻名称
            cover:'',//封面
            atype:'',//类型
            author:'',//作者
            pubilshDate:'',//发布时间
            afabu:false,//是否发布
            aredu:0,//热度
            fanwen:0,//访问量
            content:[]
          },
          this.dialogFormVisible = true
          this.$message({
            message: '保存成功！',
            type: 'success'
          });
        }else{
          this.$message({
            message: res.message,
            type: 'error'
          });
        }
      }).catch(err => {
        this.fullscreenLoading = false
        this.$message({
            message: err,
            type: 'error'
          });
      })
    },
    query(){
      this.dialogFormVisible = true
      this.fullscreenLoading = true
      this.$http.post('/artcate/bianji_details',{aid:this.editid}).then(res => {
        this.fullscreenLoading = false
        if(res.status == 0){
          res.message[0].content.forEach(item =>{
            item.sign = true
          })
          this.dialogform = res.message[0]
        }else{
          this.$message({
            message: res.message,
            type: 'error'
          });
        }
      }).catch(err => {
        this.fullscreenLoading = false
        this.$message({
            message: err,
            type: 'error'
          });
      })
    }
  }
}
</script>
<style scoped>
.newsadd{
  width: 100%;
  background-color: white;
  padding-bottom: 20px;
}
.addbutton{
  display: flex;
  position: fixed;
  padding: 20px;
  right: 20px;
  z-index: 1999;
  bottom: 20px;
}
.namediv{
  display: flex;
  padding-top:30px;
  padding-bottom: 30px;
  justify-content: center;
  font-family: Arial, Helvetica, sans-serif;
}
.nameinput1{
  padding: 0 20% 20px 20%;
  font-size: 2.5em;
  font-weight: bold;
}
.content{
  margin: 0 20% 10px 20%;
  font-size: 17px;
  line-height: 24px;
  color: rgb(71, 70, 70);
}
.contentText{
  word-wrap: break-word;
  word-break: break-all;
  overflow: hidden;
}
.contentImg{
  display: flex;
  justify-content: center;
}
.imgdiv{
  padding:0 30px 0 30px;
}
.contentImgname{
  display: flex;
  padding-bottom: 20px;
  justify-content: center;
}
.addtext{
  margin: 0 20% 60px 20%;
}
.addinput{
  width: 100%;
  outline: none;
  min-height: 100px;
  word-break:break-all;
  font-size: 17px;
  color: rgb(71, 70, 70);
  font-family: Arial, Helvetica, sans-serif;
}
.addtextbutton{
  display: flex;
  justify-content: right;
}
.addimg{
  width: 220px;
  height: 100px;
  display: flex;
  align-items: center;
  justify-content: center;
  border: 1px dashed #aca8a8;
  color: #aca8a8;
  cursor: pointer;
}
.dialog{
  position: absolute;
  top: 0;
  width: 100%;
  bottom: 0;
  right: -250px;
  justify-content: center;
  background-color: rgba(0, 0, 0,0.5);
  z-index: 2000;
  display: flex;
  
  align-items: center;
}
.dialog-content{
  width: 500px;
  padding: 30px;
  margin-right: 15%;
  background-color: white;
}
.dialog-footer{
  display: flex;
  justify-content: flex-end;
}
.diglog-name{
  font-family: Helvetica Neue,Helvetica,PingFang SC,Hiragino Sans GB,Microsoft YaHei,SimSun,sans-serif;
  font-size: 18px;
  color: #303133;
  line-height: 24px;
  padding-bottom: 30px;
}
</style>